import { BaseManager } from '../libs/rxjs/cc3/BaseManager';
import { _decorator, director, color, System, native, sys, macro } from 'cc';
const { ccclass, property } = _decorator;

// const URL = 'https://agora-token-server-tg8z.onrender.com';
// const URL = 'http://47.105.78.29:8081';

@ccclass('ClipboardManager')
class ClipboardManager extends BaseManager {

    public static instance: ClipboardManager;
    static ID = 'clipboard_service';
    get logColorOverride() { return color().fromHEX('#EEDDCC') };

    static registerSystem() {
        director.unregisterSystem(director.getSystem(ClipboardManager.ID));
        director.registerSystem(ClipboardManager.ID, clipboardm, System.Priority.MEDIUM);
        clipboardm.init();
    }

    static unregisterSystem() {
        clipboardm.destroy();
        director.unregisterSystem(director.getSystem(ClipboardManager.ID));
    }

    CopyToClipboard(text: string) {
        if (sys.isNative) {
            if (sys.platform == sys.Platform.ANDROID) {
                native.reflection.callStaticMethod("com/cocos/game/ClipboardService", "CopyToClipboard", "(Ljava/lang/String;)V", text);
            } else if (sys.platform == sys.Platform.IOS) {
                native.reflection.callStaticMethod("ClipboardService", "CopyToClipboard:", text);
            }
        } else if (sys.isBrowser) {
            this.copyToClipboardBrowser(text);
        }
    }

    PasteFromClipboard(): string {
        if (sys.platform == sys.Platform.ANDROID) {
            return native.reflection.callStaticMethod("com/cocos/game/ClipboardService", "PasteFromClipboard", "()Ljava/lang/String;");
        } else if (sys.platform == sys.Platform.IOS) {
            return native.reflection.callStaticMethod('ClipboardService', 'PasteFromClipboard');
        }
        return "";
    }

    copyToClipboardBrowser(text) {
        if (sys.isBrowser) {
            let textArea: any = document.getElementById("clipBoard");
            if (textArea === null) {
                textArea = document.createElement("textarea");
                textArea.id = "clipBoard";
                textArea.textContent = text;
                document.body.appendChild(textArea);
            }
            textArea.select();
            try {
                const msg = document.execCommand('copy') ? 'successful' : 'unsuccessful';
                this.log("已经复制到剪贴板", msg);
                document.body.removeChild(textArea);
            } catch (err) {
                this.log("复制到剪贴板失败", err);
            }
        }
    };
}

globalThis.ClipboardManager = ClipboardManager;

export const clipboardm = ClipboardManager.instance = new ClipboardManager();